package com.springcloudalibaba.apiAsyn.controller;

import com.springcloudalibaba.apiAsyn.service.MailService;
import com.springcloudalibaba.bclass.base.BaseMailEntity;
import com.springcloudalibaba.bclass.base.BaseResult;
import com.springcloudalibaba.bclass.enums.MailCategoryEnum;
import com.springcloudalibaba.bclass.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.concurrent.CompletableFuture;

/**
 * @描述: 邮件控制器
 * @作者: lixing
 * @日期 2021/6/6 12:39
 */
@RestController
@RequestMapping("/mail")
public class MailController {
    /**
     * 加载配置文件参数：发件邮箱账号
     */
    @Value("${spring.mail.username}")
    private String sender;

    /**
     * 每个账户每天最多发送10条邮件
     */
    @Value("${sendmail.limit}")
    private long sendmailLimit;

    /**
     * 每次发送邮件的时间间隔120秒
     */
    @Value("${sendmail.interval}")
    private long sendmailInterval;

    /**
     * 邮件有效时间120秒
     */
    @Value("${sendmail.effective}")
    private long sendmailEffective;

    @Resource
    private MailService mailService;

    /**
     * @描述 TODO 发送HTML格式邮件
     * @作者 lixing
     * @日期 2019/3/30 15:51
     * @Param [
     *  category 邮件类型，详见 MailCategoryEnum 枚举 【必填】
     *  attachment 邮件附件地址，多个以逗号分隔 【非必填】
     *  text 邮件内容 【必填】
     *  receiver 接收者邮箱 【必填】
     * ]
     */
    @PostMapping("sendHtmlMail")
    public BaseResult<Object> sendHtmlMail(BaseMailEntity baseMailEntity) throws Exception {
        // TODO 校验输入的账户是否合法
//            QueryWrapper<AdminVo> queryWrapperForAdmin = new QueryWrapper<>();
//            queryWrapperForAdmin.select("email,grade");
//            queryWrapperForAdmin.eq("account", entity.getCreateUserAccount());
//            AdminVo adminEntity = adminService.getOne(queryWrapperForAdmin); // 根据 account 查询管理员的 grade和email
//            if (adminEntity == null) {
//                return CompletableFuture.completedFuture(BaseResult.fail("账号输入有误"));
//            } else if (!StrUtil.isEffective(adminEntity.getEmail())) {
//                return CompletableFuture.completedFuture(BaseResult.fail("账户邮件地址为空，请前往个人中心添加"));
//            } else {
//                entity.setCreateUserGrade(adminEntity.getGrade());
//                entity.setReceiver(adminEntity.getEmail());
//            }

        // TODO 校验该账户是否可以发送邮件
//            QueryWrapper<BaseMailEntity> queryWrapperForMail = new QueryWrapper<>();
//            queryWrapperForMail.select("createUserAccount,createTime");
//            queryWrapperForMail.eq("createUserAccount", entity.getCreateUserAccount());
//            queryWrapperForMail.orderByDesc("createTime");
//            List<BaseMailEntity> mailEntityList = mailService.list(queryWrapperForMail);
//            if (!mailEntityList.isEmpty()) {
//                BaseMailEntity mailEntity_1 = mailEntityList.get(0);
//                if (DateUtil.dateToDateCharacter(new Date()).equals(DateUtil.dateToDateCharacter(mailEntity_1.getCreateTime()))) {
//                    if ( (System.currentTimeMillis() - mailEntity_1.getCreateTime().getTime()) < sendmailInterval) {
//                        return CompletableFuture.completedFuture(BaseResult.fail("邮件已发送，请不要重复发送"));
//                    }
//                    if (mailEntityList.size() >= sendmailLimit) {
//                        return CompletableFuture.completedFuture(BaseResult.fail("当天发送邮件上限"));
//                    }
//                } else {
//                    // 清空该账户下的所有邮件记录
//                    mailService.remove(queryWrapperForMail);
//                }
//            }

        // TODO 校验通过，可以发送邮件。根据模块名称动态生成邮件内容
        String code = StrUtil.genRandomStr("mix", 4);
        if (MailCategoryEnum.LOGIN.getCategory().equals(baseMailEntity.getCategory())) { // TODO 用户登录
            baseMailEntity.setSubject("用户登录");
            baseMailEntity.setText(MessageFormat.format("本次登录的验证码为: {0}", code));
        } else if (MailCategoryEnum.UPDATE_PWD.getCategory().equals(baseMailEntity.getCategory())) { // TODO 修改密码
            baseMailEntity.setSubject("修改密码");
            baseMailEntity.setText(MessageFormat.format("本次修改密码的验证码为: {0}", code));
        }
        //
        baseMailEntity.setSender(sender);
        CompletableFuture<Boolean> sendMailCompletableFuture = mailService.sendHtmlMail( baseMailEntity );
        CompletableFuture.allOf(sendMailCompletableFuture).join();
        return sendMailCompletableFuture.get() ? new BaseResult<>().success() : new BaseResult<>().fail("发送失败");
    }

}
